<script setup lang="ts">
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { timeFormat_2, copyToCliboard } from '@/hooks/util'
import { message } from 'ant-design-vue'
import * as accountApi from '@/api/account'
import * as promotionCenterApi from '@/api/promotionCenter'
import { useUserStore } from '@/store/modules/user'
import BillDetail from './components/BillDetail.vue'
import Exchange from './Exchange.vue'
import Record from './Record.vue'
import PointsDetail from './PointsDetail.vue'
import OldList from './OldList.vue'
import Complaint from './components/Complaint.vue'
import SystemTip from './components/SystemTip.vue'
import { useBrandStore } from '@/store/modules/brand'

const brandStore = useBrandStore()

const userStore = useUserStore()
// console.log('userStore=', userStore.userInfo)

const route = useRoute()

const BillDetailRef = ref()
const exchangeRef = ref()
const recordRef = ref()
const pointsDetailRef = ref()
const oldListRef = ref()
const complaintRef = ref()
const systemTipRef = ref()

interface Pagination {
  page: number
  pageSize: number
  total: number
  current?: number
  onChange: Function
  showSizeChanger: boolean
  showQuickJumper: boolean
}

const handlePageChange = (page: any, pageSize: any) => {
  pagination.value.pageSize = pageSize
  searchParams.value.pageSize = pageSize
}

const pagination = ref<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0,
  onChange: handlePageChange,
  showSizeChanger: true,
  showQuickJumper: true,
})
let loading = ref<boolean>(false)

interface SearchParams {
  currentPage: number
  pageSize: number
  [propName: string]: any
}
const searchParams = ref<SearchParams>({
  currentPage: pagination.value.page,
  pageSize: pagination.value.pageSize,
})

const dataSource = ref([])
const columns = [
  // {
  //   title: '用户id',
  //   key: 'userId',
  //   width: 180,
  // },
  // {
  //   title: '用户名',
  //   key: 'userName',
  //   width: 120,
  // },
  // {
  //   title: '受邀用户ID',
  //   key: 'inviteeUserId',
  //   width: 180,
  // },
  {
    title: '受邀用户名',
    key: 'inviteeUserName',
    width: 300,
  },
  {
    title: '受邀用户注册时间',
    key: 'inviteeUserTime',
    width: 220,
  },
  // {
  //   title: '操作',
  //   key: 'action',
  //   width: 200,
  //   fixed: 'right',
  //   align: 'center',
  // },
]

// 表格多选
const selectedRowKey = ref<Array<any>>([])
const selectedRow = ref<Array<object>>([])
const onSelectChange = (selectedRowKeys: any[], selectedRows: any[]) => {
  selectedRowKey.value = selectedRowKeys
  selectedRow.value = selectedRows
}

// 翻页
const changePage = (e: any) => {
  pagination.value.current = e.current
  pagination.value.pageSize = e.pageSize
  searchParams.value.currentPage = pagination.value.current as number
  getList()
}

let shareUserName = ref<string | number>('') // 上级
let code = ref<string | number>('') // 获取邀请码
let pointCard = ref<string | number>('') // 获取积分卡余额
const getBalance = async () => {
  try {
    let { state, data, message: msg } = await accountApi.getUserBalance()
    if (state === 200) {
      pointCard.value = data.pointCard
      code.value = data.code
      shareUserName.value = data.shareUserName
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// ---------------------------------------------------------

const getList = async () => {
  loading.value = true
  try {
    let {
      state,
      data,
      message: msg,
    } = await promotionCenterApi.getInviteeRecordList(searchParams.value)
    if (state === 200) {
      dataSource.value = data.list
      pagination.value.total = Number(data.totalCount)
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
  loading.value = false
}

import type { SelectProps } from 'ant-design-vue'
const changeTypeList = ref<SelectProps['options']>([
  {
    label: '积分添加',
    value: 1,
  },
  {
    label: '积分扣除',
    value: 11,
  },
])

onMounted(() => {
  getBalance()
  getList()

  if (brandStore.promotionCenterFlag) {
    systemTipRef.value.showModal(true)
  }

  // oem打开第二个tab
  if (!brandStore.promotionCenterFlag) {
    setTimeout(() => {
      activeKey.value = '2'
    }, 500)
  }
})

const formRef = ref()
interface FormState {
  name?: string
  changeType?: number
  [propName: string]: any
}
const formState = reactive<FormState>({})

// 查询
const search = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.validate().then(() => {
    // console.log('formState=', formState)
    if (formState.name) {
      searchParams.value.name = formState.name
    }
    if (formState.changeType) {
      searchParams.value.changeType = formState.changeType
    }

    getList()
  })
}

// 重置
const reset = () => {
  pagination.value.current = 1
  searchParams.value.currentPage = 1
  formRef.value.resetFields()

  formRef.value.resetFields()
  for (let key in searchParams.value) {
    if (key != 'currentPage' && key != 'pageSize')
      searchParams.value.hasOwnProperty(key) && delete searchParams.value[key]
  }

  getList()
}

let activeKey = ref<string>('1')
const changeTab = () => {
  getList()
  nextTick(() => {
    recordRef.value.getList()
    exchangeRef.value.getList()
    oldListRef.value.getList()
  })
}

const copyRule = (id: string) => {
  copyToCliboard(id)
  message.success('复制成功')
}

let oneTip = '关系绑定规则：注册系统账号时通过邀请码绑定邀请关系，一经绑定，永不更改（奖励可叠加）'
let twoTip = '推广奖励规则：直接推广注册可获得积分奖励，积分可用于兑换虚拟卡券（不限于）等'
let threeTip =
  '进阶奖励条件：被邀请用户授权闲鱼平台账号后，上下级均可获得进阶奖励积分，一个店铺可获取一次奖励'
let fourTip =
  '违规说明：为确保推广活动公平公正，让每一位推广者权益得到保障，平台严禁使用虚拟号码、接码平台等虚假注册行为，一经发现，将进行积分清零处理。请大家遵守规则，诚信参与。'

const complaint = () => {
  complaintRef.value.setVisible(true)
}
</script>

<template>
  <page-container :title="route.meta.title">
    <div>
      <a-card style="margin-bottom: 10px">
        <div class="markdown">
          <ExclamationCircleOutlined style="color: #68cb37" />
          {{ oneTip }}
        </div>
        <div class="markdown">
          <ExclamationCircleOutlined style="color: #68cb37" />
          {{ twoTip }}
        </div>
        <div style="display: flex" class="markdown">
          <div style="flex: 1">
            <ExclamationCircleOutlined style="color: #68cb37" />
            {{ threeTip }}
          </div>
          <div
            style="margin-right: 100px; font-size: 20px; position: absolute; right: 0; top: 55px"
          >
            <a>积分卡余额：{{ pointCard }}</a>
          </div>
        </div>
        <div class="markdown">
          <ExclamationCircleOutlined style="color: red" />
          {{ fourTip }}
        </div>
      </a-card>
    </div>
    <a-alert type="success" show-icon>
      <template #message>
        您的邀请码：{{ code }}
        <span v-if="brandStore.promotionCenter_Invitation_link">
          ，邀请链接：
          {{ `http://pdr-web-v2.liangpiao.net.cn/#/register?code=${code}` }}
        </span>

        <span v-if="shareUserName !== ''">（上级：{{ shareUserName }}）</span>
      </template>
    </a-alert>

    <a-card style="overflow-x: scroll; margin-top: 10px">
      <a-tabs v-model:activeKey="activeKey" @change="changeTab" style="position: relative">
        <a-tab-pane key="1" v-if="brandStore.promotionCenter_moneyChanger">
          <template #tab>
            <span style="position: relative">
              兑换中心
              <div class="hot">热</div>
            </span>
          </template>
          <Exchange ref="exchangeRef"></Exchange>
        </a-tab-pane>

        <a-tab-pane key="2" tab="直属下级">
          <!-- <div class="searchBox">
            <a-form ref="formRef" layout="inline" :model="formState" class="formClass">
              <a-form-item label="受邀用户名" name="name">
                <a-input v-model:value="formState.name" placeholder="受邀用户名" />
              </a-form-item>

              <a-form-item label="变动类型" name="changeType">
                <a-select
                  v-model:value="formState.changeType"
                  placeholder="变动类型"
                  style="width: 150px"
                  allowClear
                >
                  <a-select-option
                    v-for="(item, index) in changeTypeList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>

              <a-form-item>
                <a-button type="primary" style="border-radius: 6px" @click="search">搜索</a-button>
                <a-button @click="reset" style="border-radius: 6px">重置</a-button>
                <a-dropdown v-if="selectedRowKey.length > 0">
                  <a-button>
                    批量操作
                    <DownOutlined />
                  </a-button>
                  <template #overlay>
                    <a-menu>
                      <a-menu-item @click="copyRuleAll">批量复制</a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </a-form-item>
            </a-form>
          </div> -->
          <a-table
            style="overflow-x: scroll"
            :columns="columns"
            :data-source="dataSource"
            :pagination="pagination"
            :loading="loading"
            @change="changePage"
            rowKey="id"
            :scroll="{ x: 1000 }"
          >
            <!-- :row-selection="{ selectedRowKeys: selectedRowKey, onChange: onSelectChange }" -->
            <template #emptyText>
              <a-empty description="暂无数据" />
            </template>

            <template #headerCell="{ column }">
              <template v-if="column.key === 'id'">
                <span>id</span>
              </template>
            </template>

            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'inviteeUserName'">
                {{ record.inviteeUserName }}
              </template>

              <template v-else-if="column.key === 'inviteeUserTime'">
                {{ timeFormat_2(record.inviteeUserTime) }}
              </template>
              <!-- <template v-if="column.key === 'userId'">
                <div style="width: 180px">
                  {{ record.userId }}
                </div>
              </template>

              <template v-else-if="column.key === 'userName'">
                <div style="width: 120px">
                  {{ record.userName }}
                </div>
              </template>

              <template v-else-if="column.key === 'inviteeUserId'">
                <div style="width: 180px">
                  {{ record.inviteeUserId }}
                </div>
              </template>

              <template v-else-if="column.key === 'name'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '120px' }">
                  <a-descriptions-item label="受邀用户名">{{ record.name }}</a-descriptions-item>
                  <a-descriptions-item label="创建时间">
                    {{ timeFormat_2(record.createTime) }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'changeType'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="变动类型">
                    <a-tag color="blue" v-if="record.changeType == 1">积分添加</a-tag>
                    <a-tag color="red" v-if="record.changeType == 11">积分扣除</a-tag>
                  </a-descriptions-item>
                  <a-descriptions-item label="变动积分">
                    {{ record.changeIntegral }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'changeRemark'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="备注">
                    <a-tooltip placement="top">
                      <template #title>
                        <span>{{ record.changeRemark }}</span>
                      </template>
                      <span class="hiddenText">{{ record.changeRemark }}</span>
                    </a-tooltip>
                  </a-descriptions-item>
                  <a-descriptions-item label="更新时间">
                    {{ timeFormat_2(record.updateTime) }}
                  </a-descriptions-item>
                </a-descriptions>
              </template>

              <template v-else-if="column.key === 'beforeIntegral'">
                <a-descriptions bordered size="small" :column="1" :labelStyle="{ width: '100px' }">
                  <a-descriptions-item label="变动前">
                    {{ record.beforeIntegral }}
                  </a-descriptions-item>
                  <a-descriptions-item label="变动后">
                    {{ record.afterIntegral }}
                  </a-descriptions-item>
                </a-descriptions>
              </template> -->

              <template v-else-if="column.key === 'action'">
                <div style="width: 180px"></div>
              </template>
            </template>
          </a-table>
        </a-tab-pane>

        <a-tab-pane key="3" tab="兑换记录">
          <Record ref="recordRef"></Record>
        </a-tab-pane>

        <a-tab-pane key="4" tab="积分明细">
          <PointsDetail ref="pointsDetailRef"></PointsDetail>
        </a-tab-pane>

        <a-tab-pane key="5" tab="(旧)直属下级">
          <OldList ref="oldListRef"></OldList>
        </a-tab-pane>
      </a-tabs>
      <div style="position: absolute; right: 100px; top: 20px">
        <a-button danger @click="complaint">投诉与反馈</a-button>
      </div>
    </a-card>
    <Complaint ref="complaintRef"></Complaint>
    <SystemTip ref="systemTipRef"></SystemTip>
  </page-container>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 140px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.searchBox {
  margin-bottom: 10px;
  display: flex;

  input {
    width: 200px;
    margin-right: 10px;
  }

  button {
    margin-right: 10px;
  }
}

.markdown {
  margin-bottom: 5px;
}

.hot {
  background: red;
  color: #fff;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  text-align: center;
  position: absolute;
  top: -5px;
  right: -15px;
}
</style>
